package com.lkd.handler;

import com.lkd.business.MsgHandler;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.SupplyChannel;
import com.lkd.contract.SupplyContract;
import com.lkd.emq.Topic;
import com.lkd.exception.LogicException;
import com.lkd.feign.VMService;
import com.lkd.http.vo.TaskDetailsViewModel;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskService;
import com.lkd.utils.JsonUtil;
import com.lkd.vo.VmVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 创建补货工单
 * 售货机自动补货
 */
@Component
@Slf4j
@Topic(TopicConfig.TASK_SUPPLY_TOPIC)
public class SupplyTaskHandler implements MsgHandler {
    @Autowired
    private TaskService taskService;
    @Autowired
    private VMService vmService;

    @Override
    public void process(String jsonMsg) throws IOException {
        //参数效验
        if (StringUtils.isBlank(jsonMsg) || jsonMsg == "") {

            throw new LogicException("工单协议参数错误");
        }
        SupplyContract supplyContract = JsonUtil.getByJson(jsonMsg, SupplyContract.class);
        //获取售货机编号
        String innerCode = supplyContract.getInnerCode();
        //获取补货详情
        List<SupplyChannel> supplyChannels = supplyContract.getSupplyData();

        //补货详情转换
        List<TaskDetailsViewModel> taskDetailsViewModels = supplyChannels.stream().map(supplyChannel -> {
            TaskDetailsViewModel taskDetailsViewModel = new TaskDetailsViewModel();
            BeanUtils.copyProperties(supplyChannel, taskDetailsViewModel);
            taskDetailsViewModel.setChannelCode(supplyChannel.getChannelId());
            taskDetailsViewModel.setExpectCapacity(supplyChannel.getCapacity());


            return taskDetailsViewModel;
        }).collect(Collectors.toList());

        TaskViewModel taskViewModel = new TaskViewModel();

        try {

            //通过售货机编号,获取所在区域RegionId
            VmVO vmInfo = vmService.getVMInfo(innerCode);
            //获取最少工单数员工
            int leastUserId = taskService.getLeastUser(vmInfo.getRegionId(), false);
            //执行人Id
            taskViewModel.setUserId(leastUserId);
            taskViewModel.setDesc("自动运营工单");
            taskViewModel.setInnerCode(innerCode);
            taskViewModel.setProductType(VMSystem.TASK_TYPE_SUPPLY);//补货工单
            taskViewModel.setCreateType(0);//自动工单
            //工单详情
            taskViewModel.setDetails(taskDetailsViewModels);
            taskService.addTask(taskViewModel);
        } catch (Exception e) {
            log.error("创建自动补货工单失败，msg is:" + jsonMsg);
        }

    }
}
